package com.kaifamiao.udp;
import java.io.*;
import java.net.*;

public class FolderSender {
    // 设置每个数据包的大小为1024字节
    private final static int PACKET_SIZE = 1024;
    private final static int PORT = 9999;  // 定义端口号为私有常量

    public static void main(String[] args) throws IOException {

        String receiverAddress = "127.0.0.1";  // 获取接收者地址
        DatagramSocket socket = new DatagramSocket();  // 创建UDP套接字
        InetAddress address = InetAddress.getByName(receiverAddress);  // 获取接收者的IP地址对象

        // 获取文件夹中的所有文件
        File folder = new File("/Users/linrui/a/");
        File[] listOfFiles = folder.listFiles();

        // 遍历所有文件并发送
        for (File file : listOfFiles) {
            if (file.isFile()) {
                System.out.println(file.getName());
                sendFile(file, socket, address);
            }
        }

        socket.close();  // 关闭套接字
        System.out.println("文件发送成功。");
    }

    // 发送单个文件的函数
    private static void sendFile(File file, DatagramSocket socket, InetAddress address) throws IOException {
        // 获取文件名的字节数组
        byte[] filenameBytes = file.getName().getBytes("UTF-8");

        // 发送文件名长度信息
        String headerLength = "NAMELEN:" + filenameBytes.length + ":";
        socket.send(new DatagramPacket(headerLength.getBytes("UTF-8"), headerLength.length(), address, PORT));

        // 发送文件名
        socket.send(new DatagramPacket(filenameBytes, filenameBytes.length, address, PORT));

        // 开始发送文件内容
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[PACKET_SIZE];
        int bytesRead;

        while ((bytesRead = fis.read(buffer)) != -1) {
            DatagramPacket packet = new DatagramPacket(buffer, bytesRead, address, PORT);
            socket.send(packet);
        }
        fis.close();  // 关闭文件输入流

        // 发送文件结束标志
        String end = "END:";
        socket.send(new DatagramPacket(end.getBytes(), end.length(), address, PORT));
    }
}
